package net.njcp.mybatis.frame.builder;

import net.njcp.mybatis.frame.utils.MapUtil;
import net.njcp.mybatis.frame.utils.MatchesUtil;
import net.njcp.mybatis.frame.utils.QueryUtil;
import net.njcp.mybatis.frame.utils.ReflectUtil;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

/**
 * @ClassName InsertSqlBuilder
 * @Description: 针对单个对象的填加操作
 * @Author 柳拓
 * @Date 2019/11/6
 * @Version V1.0
 **/
public class InsertSqlBuilder {

    public static SQL buildInsertSql(Object object) {
        return new SQL() {{
            Class entityClass = object.getClass();
            String tableName = QueryUtil.getTableName(entityClass);
            //表名称构造
            StringBuilder tableBuilder = new StringBuilder();
            tableBuilder.append(tableName);
            INSERT_INTO(tableBuilder.toString());
            try {
                values(this, entityClass, MapUtil.Obj2Map(object));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }};
    }

    public static void values(SQL sql, Class entityClass, Map<String, Object> map) {
        String primaryKey = ReflectUtil.getPrimaryKey(entityClass);
        map.entrySet().stream().filter(e -> e.getValue() != null).forEach(
                e -> {
                    String fieldName = MatchesUtil.switchParam(e.getKey());
                    //如果当前字段不是主键或者，当前字段不是继承Comparable接口
                    if (!e.getKey().equals(primaryKey) || !(e.getValue() instanceof Comparable)) {
                        //判断如果属性是对象类型（联合主键），将对象转为Map
                        if (!(e.getValue() instanceof Comparable)) {
                            try {
                                MapUtil.Obj2Map(e.getValue()).entrySet().stream().filter(f -> f.getValue() != null).forEach(
                                        (f) -> {
                                            sql.VALUES(MatchesUtil.switchParam(f.getKey()), "#{" + e.getKey()+"."+f.getKey() + "}");
                                        }
                                );
                            } catch (Exception ex) {
                                throw new RuntimeException(ex.getMessage());
                            }
                        } else {
                            sql.VALUES(fieldName, "#{" + e.getKey() + "}");
                        }
                    }
                }
        );

    }
}
